﻿using Infrastructure;
using Infrastructure.TreeJqGrid;
using OpenAuth.App;
using OpenAuth.Domain.Core;
using OpenAuth.Mvc.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OpenAuth.Mvc.Controllers
{
    public class OrganizeManagerController : BaseController
    {
        //组合应用层
        public OrganizeManagerApp App { get; set; }


        // GET: Sort
        [Authenticate]
        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 加载分类下面的所有分类
        /// </summary>
        public string Load(Guid parentId, int page = 1, int rows = 30)
        {
            return JsonHelper.Instance.Serialize(App.Load(parentId, page, rows));
        }

        public string LoadForTree()
        {
            return JsonHelper.Instance.Serialize(App.LoadAll());
        }

        //添加或修改Category
        [HttpPost]
        public string Add(Organize model)
        {
            try
            {
                App.AddOrUpdate(model);
            }
            catch (Exception ex)
            {
                Result.Status = false;
                Result.Message = ex.Message;
            }
            return JsonHelper.Instance.Serialize(Result);
        }
        [HttpPost]
        public string Delete(Guid[] ids)
        {
            try
            {
                App.Delete(ids);
            }
            catch (Exception e)
            {
                Result.Status = false;
                Result.Message = e.Message;
            }

            return JsonHelper.Instance.Serialize(Result);
        }




        [HttpGet]
        public ActionResult GetTreeGridJson(string keyword = "")
        {
            var data = App.LoadAll();
            if (!string.IsNullOrEmpty(keyword))
            {
                data = data.TreeWhere(t => t.Name.Contains(keyword));
            }
            var treeList = new List<TreeGridModel>();
            foreach (Organize item in data)
            {
                //item.ParentId = item.ParentId ?? Guid.Empty;
                TreeGridModel treeModel = new TreeGridModel();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                treeModel.id = item.Id.ToString();
                treeModel.isLeaf = hasChildren;
                treeModel.parentId = item.ParentId==null?"0": item.ParentId.ToString();
                treeModel.expanded = hasChildren;
                treeModel.entityJson = item.ToJson();
                treeModel.entityJson=treeModel.entityJson.Replace("\"ParentId\":null", "\"ParentId\":\"0\"");
                treeList.Add(treeModel);
            }
        
            return Content(treeList.TreeGridJson());
        }

    }
}